package org.footballmanager.pandafootball.system.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.footballmanager.pandafootball.common.constants.Constants;
import org.footballmanager.pandafootball.common.util.DateUtils;
import org.footballmanager.pandafootball.system.dao.FootMissionDao;
import org.footballmanager.pandafootball.system.domain.FootMission;
import org.footballmanager.pandafootball.system.domain.FootMissionHistory;
import org.footballmanager.pandafootball.system.domain.FootSj;
import org.footballmanager.pandafootball.system.domain.FootUser;
import org.footballmanager.pandafootball.system.domain.enums.SJZT;
import org.footballmanager.pandafootball.system.form.impl.FootMissionSearchForm;
import org.footballmanager.pandafootball.system.mapper.FootMissionMapper;
import org.footballmanager.pandafootball.system.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Slf4j
@Service("footMissionService")
public class FootMissionServiceImpl extends ServiceImpl<FootMission> implements FootMissionService {
	private static final String MISSIONNAME = "missionName";
	@Autowired
	private FootMissionDao footMissionDao;
    @Autowired
    private FootMissionMapper footMissionMapper;
	@Autowired
	private FootMissionHistoryService footMissionHistoryService;
	@Autowired
	private FootBfinfoService footBfinfoService;
	@Autowired
	private FootUserService footUserService;
	@Autowired
	private FootZjService footZjService;
	@Autowired
	private FootSjService footSjService;

	@Override
	public void addNewMission(SJZT sjzt, HttpServletRequest request) {
		List<FootMission> missionList = this.getall();
		if(missionList != null && !missionList.isEmpty()){
			for(FootMission mission: missionList){
				if(!mission.getComplete()){
					mission.setComplete(true);
					this.updateNotNull(mission, request);
				}
				FootMissionHistory history = new FootMissionHistory();
				BeanUtils.copyProperties(history, mission);
				footMissionHistoryService.save(history, request);
				mission.setDelFlag(1);
				mission.setDelId((Long)request.getSession().getAttribute(Constants.USERID));
				mission.setDelTime(new Date());
				footMissionDao.updateByPrimaryKeySelective(mission);
			}
		}
		List<FootUser> list = footUserService.findGameIdIsNotNull();
		for(FootUser user: list){
			saveNewMissionToTable(user, sjzt, request);
		}
	}

	private void saveNewMissionToTable(FootUser user, SJZT sjzt, HttpServletRequest request){
		if(user.getJoins()){
			if(sjzt.equals(SJZT.NORMAL)){
				saveNewMission("每日常规赛任务", "每天进行1场常规赛，完成即可领取奖励5PB", 1, user, request);
			}else{
				saveNewMission("每日排位赛任务", "每天进行2场排位赛，完成即可领取奖励5PB", 2, user, request);
			}
			saveNewMission("每日热身赛任务", "每天进行2场热身赛，完成即可领取奖励5PB", 2, user, request);
		}
	}

	private void saveNewMission(String missionName, String missionDetail, Integer num,
								FootUser user, HttpServletRequest request){
		FootMission mission = new FootMission();
		mission.setComplete(false);
		mission.setMissionName(missionName);
		mission.setMissionNum(num);
		mission.setMissionDetail(missionDetail);
		mission.setUserId(user.getId());
		this.save(mission, request);
	}

	@Override
	public void finishMission(Long userId, boolean isReshen, HttpServletRequest request) {
		FootMission mission;
		if(isReshen){
			mission = findMissionByUserIdandStatus(userId, null);
		}else{
			FootSj sj = footSjService.get(footSjService.getSj());
			mission = findMissionByUserIdandStatus(userId, sj.getSjzt());
		}
		if(null != mission){
			mission.setMissionNum(mission.getMissionNum() - 1);
			this.updateNotNull(mission, request);
		}
	}

	@Override
	public FootMission findMissionByUserIdandStatus(Long userId, SJZT sjzt) {
		Example example = new Example(FootMission.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo(Constants.USERID, userId);
		Date date = new Date();
		criteria.andBetween("createTime",  DateUtils.processWithStartOrEnd(date, true), DateUtils.processWithStartOrEnd(date, false));
		if(null != sjzt){
			if(sjzt.equals(SJZT.NORMAL)){
				criteria.andLike(MISSIONNAME, "%常规赛%");
			}else{
				criteria.andLike(MISSIONNAME, "%排位赛%");
			}
		}else{
			criteria.andLike(MISSIONNAME, "%热身赛%");
		}
		return this.findByExample(example);
	}

	@Override
	public List<FootMission> findMissionsByUserId(Long userId) {
        Example example = new Example(FootMission.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo(Constants.USERID, userId);
		return this.findall(example);
	}

	@Override
	public void getMissionMoney(Long userId, boolean isReshen, HttpServletRequest request) {
		FootMission mission;
		int missionnum;
		if(isReshen){
			missionnum = footBfinfoService.countMissionNumByUserId(userId, 2);
			mission = findMissionByUserIdandStatus(userId, null);
		}else{
			missionnum = footBfinfoService.countMissionNumByUserId(userId, 1);
			FootSj sj = footSjService.get(footSjService.getSj());
			mission = findMissionByUserIdandStatus(userId, sj.getSjzt());
		}
		if(null != mission && !mission.getComplete() && mission.getMissionNum() <= missionnum){
			mission.setComplete(true);
			this.updateNotNull(mission, request);
			footZjService.getMissionMoney(userId, 5D, isReshen, request);
		}
	}

    /**
     * 翻页方法
     *
     * @param footMissionSearchForm 条件
     * @return 列表
     */
    @Override
    public List<FootMission> findall(FootMissionSearchForm footMissionSearchForm) {
        return footMissionMapper.findall(footMissionSearchForm);
    }

	/**
	 * 根据主键获取记录
	 * @param id 主键
	 * @return 记录
	 */
	@Override
	public FootMission get(Serializable id) {
		return footMissionMapper.findById(id);
	}

    /**
     * 查询
     *
     * @param entityname            实体类名
     * @param map                   参数
     * @param footMissionSearchForm 条件
     */
    @Override
    public void search(String entityname, Model map, FootMissionSearchForm footMissionSearchForm) {
        map.addAttribute(String.format(Constants.FORMNAME, entityname), footMissionSearchForm);
        Page<FootMission> page = PageHelper.startPage(footMissionSearchForm.getPageIndex(), footMissionSearchForm.getPageSize());
        List<FootMission> list = this.findall(footMissionSearchForm);
        map.addAttribute(Constants.PI, page.toPageInfo());
        map.addAttribute(String.format(Constants.LISTENTITY, entityname), list);
    }
}
